package io.zhengsh.vvip.leetcode.recall;

import java.util.*;

public class Q51_N_Queens {

    public static void main(String[] args) {

    }

    static class Solution {
        public List<List<String>> solveNQueens(int n) {
            List<List<String>> ans = new ArrayList<>();
            int[] queens = new int[n];
            Arrays.fill(queens, -1);
            Set<Integer> columns = new HashSet<Integer>();
            Set<Integer> digonals1 = new HashSet<Integer>();
            Set<Integer> digonals2 = new HashSet<Integer>();
            backtrack(ans, queens, n, 0, columns, digonals1, digonals2);
            return ans;
        }

        public void backtrack(List<List<String>> ans, int[] queens,
                              int n, int row, Set<Integer> columns,
                              Set<Integer> digonals1, Set<Integer> digonals2) {

            if (row == n) {
                List<String> board = generatBoard(queens, n);
                ans.add(board);
            } else {
                for (int i = 0; i < n; i++) {
                    if (columns.contains(i)) {
                        continue;
                    }
                    int diagonal1 = row - i;
                    if (digonals1.contains(diagonal1)) {
                        continue;
                    }
                    int diagonal2 = row + i;
                    if (digonals2.contains(diagonal2)) {
                        continue;
                    }
                    queens[row] = i;
                    columns.add(i);
                    digonals1.add(diagonal1);
                    digonals2.add(diagonal2);
                    backtrack(ans, queens, n, row + 1, columns, digonals1, digonals2);
                    queens[row] = -1;
                    columns.remove(i);
                    digonals1.remove(diagonal1);
                    digonals2.remove(diagonal2);
                }
            }
        }

        public List<String> generatBoard(int[] queens, int n) {
            List<String> board = new ArrayList<>();
            for (int i = 0; i < n; i++) {
                char[] row = new char[n];
                Arrays.fill(row, '.');
                row[queens[i]] = 'Q';
                board.add(new String(row));
            }
            return board;
        }
    }
}
